﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using UCHENG.FILEHASH.UTILS.ADB;
using UCHENG.FILEHASH.UTILS;
using System.Reflection;

namespace UCHENG.Moduler
{
    public partial class frmMain : Form
    {
        private const string PLAYERCODE = "PlayerCode";
        private const string PLAYERVERSION = "PlayerVersion";
        private const string PPTPLAYERPATH = "101PPTPlayer";
        private const string PHONEPLAYERPATH = "PhonePlayer";

        private const string PPTPLAYERPATHDIR = "101Player";
        private const string DEVELOPERDIST = "DeveloperDist";
        private string[] devs;

        public string Tab2ConfigPath
        {
            get
            {
                return System.Environment.CurrentDirectory + "\\" + "tab2_config.json";
            }
        }

        public string Tab1ConfigPath
        {
            get
            {
                return System.Environment.CurrentDirectory + "\\" + "tab1_config.json";
            }
        }

        public string DeviceId { get; set; }

        /// <summary>
        /// 是否连接手机成功
        /// </summary>
        public bool IsSuccess { get; set; }

        #region 构造
        public frmMain()
        {
            InitializeComponent();
            initPage();

            this.Text = "颗粒小工具 " + GetRunningVersion().ToString();
            //_myweb.Navigate("file:///C:/Users/GO/Documents/Visual Studio 2010/Projects/GeoDemo/GeoDemo/geodemo.htm", NULL, NULL, NULL, NULL);
            webBrowser1.Navigate("file:///" + System.Environment.CurrentDirectory + "\\readme.md");

            if (chkAuto.Checked)
            {
                timer1.Tick += new EventHandler(timer1_Tick);
                timer1.Interval = 10000;
                timer1.Start();
            }
            else
            {
                if (timer1 != null)
                {
                    timer1.Stop();
                }
            }
        }

        #endregion
       
        #region 方法
        private Version GetRunningVersion()
        {
            try
            {
                return System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion;
            }
            catch
            {
                return Assembly.GetExecutingAssembly().GetName().Version;
            }
        }

        private void initPage()
        {
            var playerCode = ConfigurationManager.AppSettings[PLAYERCODE];
            var playerVersion = ConfigurationManager.AppSettings[PLAYERVERSION];
            var pcPlayerPath = ConfigurationManager.AppSettings[PPTPLAYERPATH];
            var phonePlayerPath = ConfigurationManager.AppSettings[PHONEPLAYERPATH];

            var pcPlayerDir = ConfigurationManager.AppSettings[PPTPLAYERPATHDIR];
            var devloperDist = ConfigurationManager.AppSettings[DEVELOPERDIST];

            txtCode.Text = playerCode;
            txtVersion.Text = playerVersion;
            txtPcPlayerPath.Text = pcPlayerPath;
            txtPhonePlayerPath.Text = phonePlayerPath;


            txtPhonePlayerPresenter.Text = phonePlayerPath;
            txtPcPlayerPresenter.Text = pcPlayerDir;
            txtDist.Text = devloperDist;


            if (File.Exists(Tab1ConfigPath))
            {
                string configText = File.ReadAllText(Tab1ConfigPath);
                string[] configs = configText.Split('|');
                txtCode.Text = configs[0];
                txtVersion.Text = configs[1];
                txtPcPlayerPath.Text = configs[2];
                txtPhonePlayerPath.Text = configs[3];
                try
                {
                    chkReplace.Checked = Convert.ToBoolean(Convert.ToInt32(configs[4]));
                }
                catch
                {
                    chkReplace.Checked = false;
                }

                try
                {
                    chkReplacePhone.Checked = Convert.ToBoolean(Convert.ToInt32(configs[5]));
                }
                catch
                {
                    chkReplacePhone.Checked = false;
                }

            }

            if (File.Exists(Tab2ConfigPath))
            {
                string configText = File.ReadAllText(Tab2ConfigPath);
                string[] configs = configText.Split('|');
                txtSolution.Text = configs[0];
                txtCodes.Text = configs[1];
                txtDist.Text = configs[2];
                txtPcPlayerPresenter.Text = configs[3];
                txtPhonePlayerPresenter.Text = configs[4];

                try
                {
                    chkAuto.Checked = Convert.ToBoolean(Convert.ToInt32(configs[5]));
                }
                catch
                {
                    chkAuto.Checked = false;
                }
            }

            startAdbServer();

        }

        private void startAdbServer()
        {
            string message = string.Empty;
            //启动服务
            if (!AdbHelper.StartServer(Application.StartupPath))
            {
                message = "服务启动失败！";
                lblMessagePlayer.Text = message;
                lblMessagePlayer.ForeColor = Color.Red;
                lblMessagePresenter.Text = message;
                lblMessagePresenter.ForeColor = Color.Red;
                IsSuccess = false;
                return;
            }

            //获取设备列表
            devs = AdbHelper.GetDevices();
            if (devs.Length == 0)
            {
                message = "没有连接设备！";
                lblMessagePlayer.Text = message;
                lblMessagePlayer.ForeColor = Color.Red;
                lblMessagePresenter.Text = message;
                lblMessagePresenter.ForeColor = Color.Red;
                IsSuccess = false;
                return;
            }

            if (devs.Length > 0)
            {
                DeviceId = devs[0];
            }


            message = "成功连接设备！";
            lblMessagePlayer.ForeColor = Color.Green;
            lblMessagePlayer.Text = message;
            lblMessagePresenter.ForeColor = Color.Green;
            lblMessagePresenter.Text = message;
            IsSuccess = true;
        }

        private void autoCover()
        {
            string solution = txtSolution.Text;
            string[] codes = txtCodes.Text.Split(',');
            string phonePlayer = txtPhonePlayerPresenter.Text;
            foreach (string code in codes)
            {
                string filePath = string.Format(txtDist.Text, solution, code);

                if (!FileService.Exists(filePath))
                {
                    return;
                }

                string dirPath = string.Format(txtPcPlayerPresenter.Text, code);
                if (!FileService.DirExists(dirPath))
                {
                    return;
                }

                string fileName = Path.GetFileName(filePath);


                string path2 = dirPath + "\\" + fileName;

                bool hashEqual = FileService.CompareFile(filePath, path2);
                if (!hashEqual)
                {
                    File.Copy(filePath, dirPath + "\\" + fileName, true);

                    if (File.Exists(Tab2ConfigPath))
                    {
                        File.Delete(Tab2ConfigPath);
                    }
                }

                string phoneDirPath = string.Format(txtPhonePlayerPresenter.Text, code);
                if (IsSuccess)
                {
                    AdbHelper.CopyFileToDevice(DeviceId, filePath, phoneDirPath);
                }

            }
        }
        #endregion

        #region 事件
        void timer1_Tick(object sender, EventArgs e)
        {
            autoCover();
        }
        private void btnReplacePlayer_Click(object sender, EventArgs e)
        {
            btnReplacePlayer.Enabled = false;

            DownloadService downloadService = new DownloadService();
            downloadService.Excute(new PlayerVo()
            {
                DeviceId = DeviceId,
                IsReplace = chkReplace.Checked,
                IsReplacePhone = chkReplacePhone.Checked,
                PhonePlayerPath = txtPhonePlayerPath.Text,
                PlayerCode = txtCode.Text,
                PlayerPath = txtPcPlayerPath.Text,
                PlayerVersion = txtVersion.Text
            });


            File.WriteAllText(Tab1ConfigPath, txtCode.Text + "|" + txtVersion.Text + "|" + txtPcPlayerPath.Text + "|" + txtPhonePlayerPath.Text + "|" + (chkReplace.Checked == true ? "1" : "0") + "|" + (chkReplacePhone.Checked == true ? "1" : "0"));

            btnReplacePlayer.Enabled = true;

            MessageBox.Show("替换完成", "提示");
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            initPage();
        }

        private void btnReplacePresenter_Click(object sender, EventArgs e)
        {
            btnReplacePresenter.Enabled = false;

            string solution = txtSolution.Text;

            string[] codes = txtCodes.Text.Split(',');

            string phonePlayer = txtPhonePlayerPresenter.Text;

            foreach (string code in codes)
            {
                string filePath = string.Format(txtDist.Text, solution, code);

                if (!FileService.Exists(filePath))
                {
                    MessageBox.Show("文件不存在, 编码：" + code, "提示");
                    return;
                }

                string dirPath = string.Format(txtPcPlayerPresenter.Text, code);
                if (!FileService.DirExists(dirPath))
                {
                    MessageBox.Show("PcPlayer目录不存在", "提示");
                    return;
                }


                string fileName = Path.GetFileName(filePath);

                File.Copy(filePath, dirPath + "\\" + fileName, true);

                if (File.Exists(Tab2ConfigPath))
                {
                    File.Delete(Tab2ConfigPath);
                }

                File.WriteAllText(Tab2ConfigPath, solution + "|" + code + "|" + txtDist.Text + "|" + txtPcPlayerPresenter.Text + "|" + txtPhonePlayerPresenter.Text + "|" + chkAuto.Checked);


                string phoneDirPath = string.Format(txtPhonePlayerPresenter.Text, code);
                if (IsSuccess)
                {
                    AdbHelper.CopyFileToDevice(DeviceId, filePath, phoneDirPath);
                }

            }
            btnReplacePresenter.Enabled = true;
            MessageBox.Show("替换完成", "提示");
        }
        #endregion
    }
}
